package com.jiehoo.elove.dao.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.jiehoo.elove.dao.BaseDAO;
import com.jiehoo.elove.model.Base;

public class BaseJDO implements BaseDAO {

	public void create(Base object) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(object);
		} finally {
			pm.close();
		}
	}

	public <T> T get(Class<T> c, String id) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
		T base = null;
		try {
			base = pm.getObjectById(c, id);
		} finally {
			pm.close();
		}
		return base;
	}

	public void update(Base object) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(object);
		} finally {
			pm.close();
		}
	}

	public void delete(Base object) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.deletePersistent(object);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public <T> T unique(Class<T> c, String property, String value) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
		Query query = pm.newQuery(c);
		query.setFilter(property + " == '" + value + "'");
		try {
			List<T> results = (List<T>) query.execute();
			if (results.size() == 0) {
				return null;
			} else if (results.size() == 1) {
				return results.get(0);
			} else {
				throw new RuntimeException("More than one result matched.");
			}
		} finally {
			pm.close();
		}
	}
}
